#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2023/03/14
# @Author  : Tuut
# @Email   : 49616026@qq.com
# @File    : MySchedulerConfig.py

import datetime
import threading
import time

import schedule

from schedu.ScheduleService import ScheduleService


def run_threaded(job_func):
    job_thread = threading.Thread(target=job_func)
    job_thread.start()


class MySchedulerConfig:
    run_fun = ''
    job_pool = []

    @staticmethod
    def time_printer(self):
        now = datetime.datetime.now()
        ts = now.strftime('%Y-%m-%d %H:%M:%S')
        print('do func time :', ts)

    @staticmethod
    def time_running():
        while True:
            schedule.run_pending()
            time.sleep(3)

    @staticmethod
    def start_task(in_thread):
        if in_thread:
            run_threaded(MySchedulerConfig.time_running)
        else:
            MySchedulerConfig.time_running()
        return 200

    @staticmethod
    def fetch_task(tag_name):
        result = []
        if tag_name is not None and not len(tag_name) > 0:
            jobs = schedule.get_jobs()
        else:
            jobs = schedule.get_jobs(tag_name)
        for job in jobs:
            result.append({'tags': ', '.join(list(job.tags)), 'nextRun': job.next_run, 'period': job.at_time,
                           'func': str(job.job_func).split(",")[1], 'latest': job.latest, 'should_run': job.should_run})
        return result

    @staticmethod
    def detail_task(tag_id):
        for job in MySchedulerConfig.job_pool:
            if job["id"] == int(tag_id):
                return {"id": job['id'], "tag": job['name'], "next_run": job['job'].next_run,
                        "interval": job['job'].period}

    ##
    # param run_fun 执行任务调用方法
    # param timer 调用的时间触发器，注意时间类别触发器需要 HH:MM格式
    # param timer_flg 任务脚本时间区分 1 秒, 2 分, 3小时, 4天固定时间, 9 周
    @staticmethod
    def add_task(run_fun, timer, timer_flg):
        now = int(time.mktime(datetime.datetime.now().timetuple()))
        if int(timer_flg) == 1:
            tag_name = 'seconds-tasks[%d]' % now
            job = schedule.every(int(timer)).seconds \
                .do(run_threaded, run_fun, ).tag('customer', tag_name)
            MySchedulerConfig.job_pool.append({'id': now, 'name': tag_name, 'job': job})
        elif int(timer_flg) == 2:
            tag_name = 'minutes-tasks[%d]' % now
            job = schedule.every(int(timer)).minutes \
                .do(run_threaded, run_fun).tag('customer', tag_name)
            MySchedulerConfig.job_pool.append({'id': now, 'name': tag_name, 'job': job})
        elif int(timer_flg) == 3:
            tag_name = 'hourly-tasks[%d]' % now
            job = schedule.every(int(timer)).hours \
                .do(run_threaded, run_fun).tag('customer', tag_name)
            MySchedulerConfig.job_pool.append({'id': now, 'name': tag_name, 'job': job})
        elif int(timer_flg) == 4:
            tag_name = 'day-tasks[%d]' % now
            job = schedule.every().day.at("07:15") \
                .do(run_threaded, run_fun).tag('customer', tag_name)
            MySchedulerConfig.job_pool.append({'id': now, 'name': tag_name, 'job': job})
        return 200

    ##
    # param run_fun 执行任务调用方法
    # param timer 调用的时间触发器，注意时间类别触发器需要 HH:MM格式
    # param timer_flg 任务脚本时间区分 1 秒, 2 分, 3小时, 4天固定时间, 9 周
    @staticmethod
    def add_sys_task(timer_flg):
        now = int(time.mktime(datetime.datetime.now().timetuple()))
        run_fun = ScheduleService.run_fun()
        if int(timer_flg) == 9:
            tag_name = 'gitlab-day-tasks[%d]' % now
            job = schedule.every().friday.at("03:30") \
                .do(run_threaded, run_fun, ).tag('zantao', tag_name)
        elif int(timer_flg) == 10:
            tag_name = '禅道-day-tasks[%d]' % now
            job = schedule.every().day.at("07:45") \
                .do(run_threaded, run_fun).tag('customer', tag_name)
        elif int(timer_flg) == 11:
            tag_name = '禅道-day-tasks[%d]' % now
            job = schedule.every().day.at("21:55") \
                .do(run_threaded, run_fun).tag('customer', tag_name)
        MySchedulerConfig.job_pool.append({'id': now, 'name': tag_name, 'job': job})

    @staticmethod
    def cancel_task(tag_id):
        for job in MySchedulerConfig.job_pool:
            if job["id"] == int(tag_id):
                schedule.cancel_job(job['job'])
                return 200
